#pragma once

#include "WiiCISIORoot.h"

namespace WiiCIS {
	namespace IO {
		class RootWindows : public Root {
		private:
			bool isManuallyPaired;

			HANDLE deviceHandle;
			OVERLAPPED hidOverlap;

			static void __cdecl ConnectThread(void *io);
			static void __cdecl DisconnectThread(void *io);

			void FindNext();
			void ScanDevices();
			bool TryOpenDevice(HANDLE discoveredHandle);
			void CloseDeviceHandles();

			inline GUID GetDeviceId() {
				GUID output;
				HidD_GetHidGuid(&output);

				return output;
			}

#if WIICIS_COMPILER == WIICIS_COMPILER_MSVC
			BLUETOOTH_DEVICE_INFO activeDeviceInfo;

			inline BLUETOOTH_DEVICE_SEARCH_PARAMS CreateBluetoothSearchParameters() {
				BLUETOOTH_DEVICE_SEARCH_PARAMS output;
				ZeroMemory(&output, sizeof(BLUETOOTH_DEVICE_SEARCH_PARAMS));

				output.dwSize = sizeof(BLUETOOTH_DEVICE_SEARCH_PARAMS);
				output.fReturnUnknown = true;
				output.fReturnRemembered = true;
				output.fIssueInquiry = true;
				output.cTimeoutMultiplier = 1;

				return output;
			}

			inline BLUETOOTH_DEVICE_INFO CreateBluetoothDeviceInfo() {
				BLUETOOTH_DEVICE_INFO output;
				ZeroMemory(&output, sizeof(BLUETOOTH_DEVICE_INFO));

				output.dwSize = sizeof(BLUETOOTH_DEVICE_INFO);

				return output;
			}

			inline void SetBluetoothServiceState(BLUETOOTH_DEVICE_INFO *deviceInfo, bool enabled) {
				GUID hidGuid = HumanInterfaceDeviceServiceClass_UUID;
				BluetoothSetServiceState(NULL, deviceInfo, &hidGuid, enabled ? BLUETOOTH_SERVICE_ENABLE : BLUETOOTH_SERVICE_DISABLE);
			}
#endif

		public:
			RootWindows();
			~RootWindows();

			void Connect();
			void Disconnect();

			void Read(byte *buffer);
			void Write(byte *buffer, int length);
		};
	}
}